
from django.contrib.auth.hashers import make_password, check_password
from django.core.cache import cache
from django.http import HttpResponse, JsonResponse
from django.shortcuts import render, redirect
from django.urls import reverse

from App.comm import process_food_type, send_mail_active, create_token
from App.models import MainWheel, MainNav, MainMustBuy, MainShow, FoodType, Goods, AXFUsers
from App.views_constant import *


def check_token(f):
    """实现检测登录态"""

    def wrapper(request, **kwargs):
        token = request.session.get("token")
        user_id = cache.get(token)
        if user_id:
            return f(request, **kwargs)
        else:
            return redirect(reverse("app:login"))

    return wrapper


def home(request):
    main_wheels = MainWheel.objects.all()
    main_navs = MainNav.objects.all()
    main_must_buys = MainMustBuy.objects.all()
    main_shows = MainShow.objects.all()
    data = {
        "title": "首页",
        "main_wheels": main_wheels,
        "main_navs": main_navs,
        "main_must_buys": main_must_buys,
        "main_shows": main_shows,
    }
    return render(request, 'main/home.html', context=data)


def market_with_params(request, type_id, child_id, order_rule):
    food_types = FoodType.objects.all()  # 获取全部分类，用作闪购页面左侧导航
    goods_list = Goods.objects.all().filter(category_id=type_id)
    if child_id != ALL_TYPE:
        goods_list = Goods.objects.all().filter(
            category_id=type_id).filter(
            child_id=child_id)
    if order_rule == ORDER_TOTAL:
        pass
    elif order_rule == ORDER_PRICE_UP:
        goods_list.order_by("price")
    elif order_rule == ORDER_PRICE_DOWN:
        goods_list.order_by("-price")
    elif order_rule == ORDER_SALE_UP:
        goods_list.order_by("product_num")
    elif order_rule == ORDER_SALE_DOWN:
        goods_list.order_by("-product_num")
    else:
        pass
    food_type = FoodType.objects.get(type_id=type_id)
    food_type_child_name = food_type.child_type_name
    data = {
        "title": "闪购",
        "foot_types": food_types,
        "goods_list": goods_list,
        "type_id": int(type_id),
        "food_type_child_name_list": process_food_type(food_type_child_name),
        "child_id": child_id,
        "order_rule_list": ORDER_RULE_LIST,
        "order_rule_view": order_rule,
    }
    return render(request, 'main/market.html', context=data)


def market(request):
    return redirect(reverse("app:market_with_params", kwargs={
        "type_id": 104749,
        "child_id": 0,
        "order_rule": 0,
    }))


def cart(request):
    return render(request, 'main/cart.html')


def mine(request):
    return render(request, 'main/mine.html')


def register(request):
    if request.method == "GET":
        return render(request, 'user/register.html', context={"title": "注册", })
    elif request.method == "POST":
        new_user = AXFUsers.objects.create(
            u_username=request.POST.get("username"),
            u_password=make_password(
                request.POST.get("password")),
            # 使用make_password进行简单的加密存储
            u_email=request.POST.get("email"),
            u_icon=request.FILES.get("icon"),
        )
        new_user.save()
        token = create_token(request, new_user.id, is_login=False)
        send_mail_active(
            username=request.POST.get("username"),
            token=token,
            email=request.POST.get("email")
        )
        return redirect(reverse('app:login'))


def login(request):
    token = request.session.get("token")
    user_id = cache.get(token)
    if user_id:
        redirect(reverse("app:home"))
    else:
        if request.method == "GET":
            error_message = request.session.get("error_message")
            data = {"title": "登录"}
            if error_message:
                del request.session["error_message"]
                data["error_message"] = error_message
            return render(request, 'user/login.html', context=data)
        elif request.method == "POST":
            username, password = request.POST.get("username"), request.POST.get("password")
            users = AXFUsers.objects.filter(u_username=username)
            if users.exists():
                user = users.first()
                if check_password(password, user.u_password):  # 使用check_password，进行对加密密码的校验，返回值是bool类型
                    if user.is_active == 1:
                        create_token(request, user.id, timeout=[10, 1, 1])
                        return redirect(reverse("app:home"))
                    else:
                        request.session["error_message"] = "用户尚未激活"
                        return redirect(reverse("app:login"))
                elif password == user.u_password:
                    # 兼容以前明文密码注册的用户，如果检测密码匹配得上，就进行重新加密存储
                    user.u_password = make_password(password)
                    user.save()
                    create_token(request, user.id)
                    return redirect(reverse("app:home"))
                else:
                    request.session["error_message"] = "密码错误"
                    return redirect(reverse("app:login"))
            request.session["error_message"] = "用户不存在"
            return redirect(reverse("app:login"))


def check_user(request):
    username = request.GET.get("username")
    data = {
        "static": HTTP_STATIC_OK,
        "msg": "该用户名可以使用"
    }
    if AXFUsers.objects.filter(u_username=username):
        data["static"] = USER_EXIST_ALREADY
        data["msg"] = "用户已存在"
    return JsonResponse(data=data)


def check_email(request):
    email = request.GET.get("email")
    data = {
        "static": HTTP_STATIC_OK,
        "msg": "该邮箱可以使用"
    }
    if AXFUsers.objects.filter(u_email=email):
        data["static"] = EMAIL_EXIST_ALREADY
        data["msg"] = "邮箱已存在"
    return JsonResponse(data=data)


def active(request):
    u_token = request.GET.get("u_token")
    user_id = cache.get(u_token)
    if user_id:
        user = AXFUsers.objects.filter(pk=user_id)
        user.is_active = True
        user.save()
        return redirect(reverse("app:login"))
    return HttpResponse("激活失败，清重新激活")
